#include "playlistview.h"
#include "ui_playlistview.h"
#include <QTreeWidget>
#include <QDebug>
#include "BLL/radioBLl/radiobll.h"
#include "radioView/radioview.h"
#include "config.h"
#include "settingconfig.h"
#include "playListInfoView/pathsongsview.h"
#include "log/EZQLOG.h"
#include <QMenu>
#include <QFileDialog>
#include "playListModel/myplaylistmodel.h"
#include <QInputDialog>
#include "playListInfoView/myplaylistsongsview.h"

PlayListView::PlayListView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PlayListView)
{
    ui->setupUi(this);

//    QTreev
    _myPlaylists = 0;

    initPlayLlistView();

}

PlayListView::~PlayListView()
{
    delete ui;
}
void PlayListView::refreshMyPlayList()
{
    QTreeWidgetItem *itemPlayList = 0;
    int topCount = ui->treeWidget->topLevelItemCount();
    for(int i=0;i<topCount;i++){
        QTreeWidgetItem *item = ui->treeWidget->topLevelItem(i);
        itemType type =static_cast<itemType>(item->data(0,Qt::UserRole).toInt());
        if(type == itemType_PlayLists){
            itemPlayList = item;
            break;
        }

    }
    if(itemPlayList==0){
        return;
    }

    QList<QTreeWidgetItem *> items =itemPlayList->takeChildren();//移除所有
    for(int i=0;i<items.count();i++){
        QTreeWidgetItem *ritem = items.at(i);
        delete ritem;
    }

    EZTally::EZTallyAutoPtr ptr = MyPlayListModel::shareMyPlayList(true);
    if(_myPlaylists){
        _myPlaylists->Release();
        _myPlaylists = 0;
    }
    _myPlaylists = static_cast<EZTally::EZTallyArray<MyPlayListModel*>* >(ptr.Get());
    _myPlaylists->Retain();
    for(int i=0;i<_myPlaylists->Count();i++){
        MyPlayListModel *mpm = _myPlaylists->ObjectAtIndex(i);

        QTreeWidgetItem *nitem = new QTreeWidgetItem(itemPlayList,QStringList(mpm->name()));
        nitem->setData(0,Qt::UserRole,QVariant(itemType_MyPlayList));
        nitem->setData(0,Qt::UserRole+1,QVariant(i));
        itemPlayList->addChild(nitem);
    }


}

void PlayListView::refreshDirItems()
{
    QTreeWidgetItem *itemDirs = 0;
    int topCount = ui->treeWidget->topLevelItemCount();
    for(int i=0;i<topCount;i++){
        QTreeWidgetItem *item = ui->treeWidget->topLevelItem(i);
        itemType type =static_cast<itemType>(item->data(0,Qt::UserRole).toInt());
        if(type == itemType_Dirs){
            itemDirs = item;
            break;
        }

    }
    if(itemDirs==0){
        return;
    }
    QList<QTreeWidgetItem *> items =itemDirs->takeChildren();//移除所有
    for(int i=0;i<items.count();i++){
        QTreeWidgetItem *ritem = items.at(i);
        delete ritem;
    }

    {
        SettingConfig *sc = Config::defaultConfig()->settingConfig();

        QTreeWidgetItem *subItem = new QTreeWidgetItem(itemDirs,QStringList("下载目录"));
        subItem->setData(0,Qt::UserRole,QVariant(itemType_DownLoadPath));
        itemDirs->addChild(subItem);

        QStringList dirs = sc->musicDirs();
        for(int i=0;i<dirs.count();i++){
            QString dirPath = dirs.at(i);
            QString dirName = dirPath.section("/",-1);
            QTreeWidgetItem *dirItem = new QTreeWidgetItem(itemDirs,QStringList(dirName));
            dirItem->setData(0,Qt::UserRole,QVariant(itemType_Dir));
            dirItem->setData(0,Qt::UserRole+1,QVariant(dirPath));
            itemDirs->addChild(dirItem);
        }
    }
}

void PlayListView::initPlayLlistView()
{

//    SettingConfig *sc = Config::defaultConfig()->settingConfig();

    QTreeWidgetItem *item0 = new QTreeWidgetItem(ui->treeWidget,QStringList("文件夹"));
    item0->setData(0,Qt::UserRole,QVariant(itemType_Dirs));


    QTreeWidgetItem *item1 = new QTreeWidgetItem(ui->treeWidget,QStringList("播放列表"));
    item1->setData(0,Qt::UserRole,QVariant(itemType_PlayLists));

    QTreeWidgetItem *item2 = new QTreeWidgetItem(ui->treeWidget,QStringList("电台"));
    item2->setData(0,Qt::UserRole,QVariant(itemType_Radios));
    {
        QTreeWidgetItem *subItem =new QTreeWidgetItem(item2,QStringList("所有电台"));
        subItem->setData(0,Qt::UserRole,QVariant(itemType_RadioAll));
        item2->addChild(subItem);

        subItem = new QTreeWidgetItem(item2,QStringList("最近播放"));
        subItem->setData(0,Qt::UserRole,QVariant(itemType_RadioHistory));
        item2->addChild(subItem);

        subItem = new QTreeWidgetItem(item2,QStringList("我喜欢的电台"));
        subItem->setData(0,Qt::UserRole,QVariant(itemType_RadioCollect));
        item2->addChild(subItem);
    }

    ui->treeWidget->addTopLevelItem(item1);
    ui->treeWidget->addTopLevelItem(item2);

//    connect(ui->treeWidget,SIGNAL(itemChanged(QTreeWidgetItem*,int)),this,SLOT(slot_itemChanged(QTreeWidgetItem*,int)));
    connect(ui->treeWidget,SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),this,SLOT(slot_currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));

    ui->treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->treeWidget,SIGNAL(customContextMenuRequested(const QPoint &)),this,SLOT(slot_customContextMenuRequested(const QPoint&)));
//    ui->treeWidget->addAction(action);

    refreshDirItems();
    refreshMyPlayList();
}


//void PlayListView::slot_itemChanged(QTreeWidgetItem * item, int column)
//{
//    qDebug() << item << "\n" << column ;
//}

void PlayListView::slot_currentItemChanged(QTreeWidgetItem * current, QTreeWidgetItem * )
{
//    qDebug() << current->data(0,Qt::UserRole);
    QTreeWidgetItem *topItem = current;
    while (topItem->parent()) {
        topItem = topItem->parent();
    }
    if(topItem == current){// current is top
        return;
    }
    itemType type =static_cast<itemType>(current->data(0,Qt::UserRole).toInt());
    switch (type) {
    case itemType_RadioAll:
    {
        static RadioView *radioview = new RadioView();
//        RadioView *radioview = new RadioView();
        emit sig_changeCenterWidget(radioview);
    }
        break;
    case itemType_RadioHistory:
    {
        QWidget *widget = new QWidget();
        emit sig_changeCenterWidget(widget);
    }
        break;
    case itemType_RadioCollect:
    {

        QWidget *widget = new QWidget();
        emit sig_changeCenterWidget(widget);

    }
        break;
    case itemType_DownLoadPath:
    {
        PathSongsView *songsview = new PathSongsView();
        songsview->setPath(Config::defaultConfig()->settingConfig()->downLoadPath());
        emit sig_changeCenterWidget(songsview);
    }
        break;
    case itemType_Dir:
    {
        QString dirPath = current->data(0,Qt::UserRole+1).toString();
        PathSongsView *songsview = new PathSongsView();
        songsview->setPath(dirPath);
        emit sig_changeCenterWidget(songsview);

    }
        break;
    case itemType_MyPlayList:
    {
        int index= current->data(0,Qt::UserRole+1).toInt();
        MyPlayListModel *mpm = _myPlaylists->ObjectAtIndex(index);
        if(mpm->count()==0){
            mpm->fillSongsFromDB();
        }
        MyPlayListSongsView *mpmv = new MyPlayListSongsView();
        mpmv->setMyPlaylist(mpm);
        emit sig_changeCenterWidget(mpmv);
    }
        break;
    default:
        break;
    }

}

void PlayListView::contextMenuEvent(QContextMenuEvent * event)
{
//    EZDebug << event;
}
void PlayListView::slot_customContextMenuRequested(const QPoint & pos)
{
//    EZDebug << "event" << "slot_customContextMenuRequested";
//    QPoint point = event->pos();
    QTreeWidgetItem *current =  ui->treeWidget->itemAt(pos);
    if(current ==NULL){
        return;
    }
//    ui->treeWidget->indexOfTopLevelItem(item);
    itemType type =static_cast<itemType>(current->data(0,Qt::UserRole).toInt());
//    EZDebug << type ;
    switch(type){
    case itemType_Dirs:
        showDirsMenu(pos);
        break;
    case itemType_PlayLists:
        {
            showPlayListsMenu(pos);
        }
        break;
    case itemType_MyPlayList:
        {
            int index = current->data(0,Qt::UserRole+1).toInt();
            showMyPlayListMenu(pos,index);
        }
        break;
    }
}

void PlayListView::showDirsMenu(const QPoint & pos)
{
    QMenu menu(this);
    QAction *addLocalDir = menu.addAction("添加音乐目录");

    QPoint point(pos.x(),ui->treeWidget->header()->height()+pos.y());

    QAction *action = menu.exec(ui->treeWidget->mapToGlobal(point));
    if(addLocalDir == action){
        QFileDialog fileDialod(this);
        fileDialod.setFileMode(QFileDialog::Directory);
        int accept =fileDialod.exec();
        if(accept==1){
            QString dir = fileDialod.selectedFiles().at(0);
            SettingConfig *sc = Config::defaultConfig()->settingConfig();
            sc->addMusicDir(dir);
            sc->saveToFilePath();
            refreshDirItems();
        }
    }

}

void PlayListView::showPlayListsMenu(const QPoint &pos)
{
    QMenu menu(this);
    QAction *addPlayListAction = menu.addAction("add new playlist");

    QPoint point(pos.x(),ui->treeWidget->header()->height()+pos.y());

    QAction *action = menu.exec(ui->treeWidget->mapToGlobal(point));
    if(addPlayListAction == action){

        bool ok;
        QString text = QInputDialog::getText(this, tr("新建播放列表"),tr("名字:"), QLineEdit::Normal,"", &ok);
        if (ok && !text.isEmpty()){
            MyPlayListModel *mpm = new MyPlayListModel();
            mpm->setName(text);
            mpm->saveToDB();
            refreshMyPlayList();
        }

    }
}

void PlayListView::showMyPlayListMenu(const QPoint &pos,int index)
{
    QMenu menu(this);
    QAction *action1 = menu.addAction("delete playlist");

    QPoint point(pos.x(),ui->treeWidget->header()->height()+pos.y());

    QAction *action = menu.exec(ui->treeWidget->mapToGlobal(point));
    if(action1 == action){
        MyPlayListModel *mpm = _myPlaylists->ObjectAtIndex(index);
        mpm->removeOnDB();
        refreshMyPlayList();
    }
}
